package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.CreditRepairType;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.CreditRepairTableFieldEnum;
import com.py.credit.entity.enums.CreditRepairTableFieldHeiEnum;
import com.py.credit.service.ColumnService;
import com.py.credit.service.CreditRepairService;
import com.py.credit.service.GetRoleService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.TableService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: 信用修复模块
 *
 * @author YaoS
 * @date 19/4/10 11:19
 */
@RestController
@RequestMapping(value = "/creditRepair")
public class CreditRepairController {

    private final static String FRONT_TABLE_ID = "creditFixTable";


    @Value("${absolutepath}")
    private String absolutepath;

    @Autowired
    private RemoteBaseService remoteBaseService;

    @Autowired
    private CreditRepairService creditRepairService;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private TableService tableService;
    @Autowired
    private GetRoleService getRoleService;

    /* 修复历史模块代码开始 */

    @RequestMapping(value = "/getOptionalColumns.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColumns(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId) {
        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            return new RestServiceResult<>(CreditRepairTableFieldEnum.getAdvancedConditionColumns(tableId.toString()));
        }else {
            return new RestServiceResult<>(CreditRepairTableFieldHeiEnum.getAdvancedConditionColumns(tableId.toString()));
        }
    }

    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId) {
        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            return new RestServiceResult<>(CreditRepairTableFieldEnum.getAdvancedConditionColumns(tableId.toString()));
        }else {
            return new RestServiceResult<>(CreditRepairTableFieldHeiEnum.getAdvancedConditionColumns(tableId.toString()));
        }

    }


    /**
     * 功能描述: 信用修复获取修复历史
     *
     * @param tableId 资源ID
     * @return
     * @author YaoS
     * @date 19/4/10 13:39
     */
    @RequestMapping(value = "/getTableList.json")
    public RestServiceResult<List<Map<String, Object>>> getTableList(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            Page page, HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID + "_" + tableId);
            } else {
                ExceptionLogger.error("CreditRepairController#getTableList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CreditRepairController#getTableList", "未获取到当前用户信息！");
        }
        List<String> showColumns;
        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            showColumns = (configColumns == null || configColumns.length == 0)
                    ? CreditRepairTableFieldEnum.getDefaultShowColumnEN(tableId.toString()) : Arrays.asList(configColumns);
        } else {
            showColumns = (configColumns == null || configColumns.length == 0)
                    ? CreditRepairTableFieldHeiEnum.getDefaultShowColumnEN(tableId.toString()) : Arrays.asList(configColumns);
        }
        String[] additionalColumns = {"id", "record_id"};
        List<Map<String, Object>> tableList = creditRepairService.getByConditionForPage(tableId.toString(), showColumns,
                additionalColumns, condition, page);
        return new RestServiceResult<>(page.getTotalCount(), tableList);

    }

    @RequestMapping(value = "/addShowColumns.json")
    public RestServiceResult<String> addShowColumns(@RequestParam(value = "columns", required = true) String[] columns,
                                                    @RequestParam(value = "tableId", defaultValue = "100000", required = true) String tableId,
                                                    HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID + "_" + tableId, columns);
            } else {
                ExceptionLogger.error("CreditRepairController#addShowColumns", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CreditRepairController#addShowColumns", "未获取到当前用户信息！");
        }
        return new RestServiceResult<>();
    }

    @RequestMapping(value = "/exportList.json")
    public void exportCommoncontentList(
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletResponse response) throws IOException {

        page.setLimit(1000);

        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> tableList = creditRepairService.getByConditionForPage(tableId.toString(), showColumns, null,
                condition, page);
        List<OptionalColumn> optionalColumns;

        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            optionalColumns = CreditRepairTableFieldEnum.getOptionalColumns(tableId.toString());
        }else {
            optionalColumns = CreditRepairTableFieldHeiEnum.getOptionalColumns(tableId.toString());
        }

        ExcelUtil.downloadExcel(response, tableList, "信用修复历史列表", "信用修复历史列表", showColumns, optionalColumns);

    }

    /* 修复历史模块代码结束 */

    /* 信用修复模块代码开始 */

    /**
     * 功能描述:获取展示列
     *
     * @param tableId 资源ID
     * @return 展示列
     * @author YaoS
     * @date 19/4/10 10:06
     */
    @RequestMapping(value = "/getPunishmentOptionalColumns.json")
    public RestServiceResult<List<OptionalColumn>> getPunishmentOptionalColumns(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId) {
        String[] defaultShowColumn = this.getDefaultShowColumn(tableId);
        List<OptionalColumn> optionalColumnByTableId = columnService.getOptionalColumnByTableId(tableId);
        List<OptionalColumn> filter = filter(optionalColumnByTableId, defaultShowColumn);
        return new RestServiceResult<>(filter);
    }

    /**
     * 功能描述: 获取高级查询条件列
     *
     * @param tableId 资源ID
     * @return 高级查询列信息
     * @author YaoS
     * @date 19/4/10 10:30
     */
    @RequestMapping(value = "/getPunishmentAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getPunishmentAdvancedConditionColumns(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId) {
        String[] defaultShowColumn = this.getDefaultShowColumn(tableId);
        List<OptionalColumn> optionalColumnByTableId = columnService.getOptionalColumnByTableId(tableId);
        List<OptionalColumn> filter = filter(optionalColumnByTableId, defaultShowColumn);
        return new RestServiceResult<>(filter);
    }

    /**
     * 功能描述:获取待修复数据详情信息
     *
     * @param tableId   表资源ID
     * @param condition 展示列
     * @param page      分页信息
     * @param request   request
     * @return 资源的信息
     * @author YaoS
     * @date 19/4/10 10:44
     */
    @RequestMapping(value = "/getPunishmentDataList.json")
    public RestServiceResult<List<Map<String, Object>>> getPunishmentDataList(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {
        String resourceId = tableService.queryCubeById(tableId).getResourceId();
        String[] defaultShowColumn = this.getDefaultShowColumn(tableId);
        long officeId = 0;
        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        String rolename = "";
        String deptId = "";
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
            	 configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + resourceId);
                 officeId = userInfo.getOfficeId();
                
            	//获取当前用户的角色
				List<HashMap<String,Object>> rolenames =  getRoleService.getRolesByUserId(userInfo.getId(), token).getData();   
		        for (Map<String, Object> map : rolenames) {         	
		            for (String key : map.keySet()) {
		           	 if(key.equals("roleName")) {
		           		 if(map.get(key)!=null) {
		           			 rolename = (String) map.get(key);
		           		 }
		           		 break;
		           	 }
		            }
		        }
		        if(!rolename.equals("系统管理员")) {
		        	 deptId = String.valueOf(userInfo.getOfficeId());
		        }else {
		        	deptId = "";
		        }
               
            } else {
                ExceptionLogger.error("CreditRepairController#getPunishmentDataList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CreditRepairController#getPunishmentDataList", "未获取到当前用户信息！");
        }

        List<String> columnENByTableId = columnService.getColumnENByTableId(tableId);
        List<String> filter = new ArrayList<>();
        //循环拼接展示字段
        for (String columnEN : columnENByTableId) {
            for (String defaultColumnEN : defaultShowColumn) {
                if (columnEN.equals(defaultColumnEN)) {
                    filter.add(columnEN);
                    break;
                }
            }
        }
        List<String> showColumns = (configColumns == null || configColumns.length == 0) ? filter
                : Arrays.asList(configColumns);
        String[] additionalColumns = {"record_id"};
        List<Map<String, Object>> tableList = creditRepairService.getCfRecordsByConditionForPage("t_" + resourceId,
                showColumns, additionalColumns, condition, page,deptId);
        return new RestServiceResult<>(page.getTotalCount(), tableList);
    }

    /**
     * 功能描述: 添加修复默认展示字段
     *
     * @param columns 字段列
     * @param tableId 资源id
     * @return 默认返回
     * @author YaoS
     * @date 19/4/10 10:58
     */
    @RequestMapping(value = "/addPunishmenShowColumns.json")
    public RestServiceResult<String> addPunishmenShowColumns(
            @RequestParam(value = "columns", required = true) String[] columns,
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId,
            HttpServletRequest request) {
        //获取resourceId
        String resourceId = tableService.queryCubeById(tableId).getResourceId();
        //获取用户信息
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                MapCache.set(userInfo.getId() + "_" + resourceId, columns);
            } else {
                ExceptionLogger.error("CreditRepairController#addPunishmenShowColumns", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CreditRepairController#addPunishmenShowColunms", "未获取到当前用户信息！");
        }

        return new RestServiceResult<>();
    }

    /**
     * 功能描述: 数据修复
     *
     * @param recordId    数据ID
     * @param tableId     资源ID
     * @param subjectName 主体名称
     * @param parameter1  参数1：处罚是cfSy处罚事由，黑名单是data_category数据类别
     * @param parameter2  参数2：处罚是cfWsh处罚文书号，黑名单是execute_refrence_no执行依据文号
     * @param parameter3  参数3：处罚是cfYj处罚依据，黑名单是register_date立案时间
     * @return 修复结果返回
     * @author YaoS
     * @date 19/4/10 11:21
     */
    @RequestMapping(value = "/repair.json")
    public RestServiceResult<String> repair(
            @RequestParam(value = "id", defaultValue = "") String recordId,
            @RequestParam(value = "tableId", defaultValue = "210001") Integer tableId,
            @RequestParam(value = "subjectName", defaultValue = "") String subjectName,
            @RequestParam(value = "parameter1", defaultValue = "") String parameter1,
            @RequestParam(value = "parameter2", defaultValue = "") String parameter2,
            @RequestParam(value = "parameter3", defaultValue = "") String parameter3,
            HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String deptName = null;
        String userName = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                deptName = userInfo.getOfficeName();
                userName = userInfo.getUsername();
            } else {
                ExceptionLogger.error("CreditRepairController#repair", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CreditRepairController#repair", "未获取到当前用户信息！");
        }
        String tableName = "t_" + tableService.queryCubeById(tableId).getResourceId();
        //修复旧数据
        creditRepairService.repair(recordId, tableName);
        //添加修复历史记录
        creditRepairService.addCreditRepairHistory(tableId, recordId, subjectName, deptName, userName, parameter1, parameter2, parameter3);
        return new RestServiceResult<>();
    }

    /**
     * 功能描述: 查看数据详细信息
     *
     * @param recordId 数据Id
     * @param tableId  资源Id
     * @return 数据详情
     * @author YaoS
     * @date 19/4/10 11:08
     */
    @RequestMapping(value = "/detail.json")
    public RestServiceResult<Object> detail(
            @RequestParam(value = "id", defaultValue = "", required = true) String recordId,
            @RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId) {
        String tableName = "t_" + tableService.queryCubeById(tableId).getResourceId();
        Map<String, Object> records = creditRepairService.getRecordById(recordId, tableName);
        return new RestServiceResult<>(records);
    }


    /**
     * 功能描述:excel导出资源信息
     *
     * @param tableId   资源ID
     * @param columnEN  列英文名
     * @param condition 展示列
     * @param page      分页信息
     * @param response  response
     * @param request   request
     * @author YaoS
     * @date 19/4/10 10:37
     */
    @RequestMapping(value = "/exportPunishmentList.json")
    public void exportPunishmentList(@RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId,
                                     @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
                                     @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
                                     HttpServletResponse response, HttpServletRequest request) throws IOException {

        //获取用户信息
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        long officeId = 0;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                officeId = userInfo.getOfficeId();
            } else {
                ExceptionLogger.error("CreditRepairController#exportPunishmentList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CreditRepairController#exportPunishmentList", "未获取到当前用户信息！");
        }
        //获取表名
        String resourceId = tableService.queryCubeById(tableId).getResourceId();
        String[] defaultShowColumn = getDefaultShowColumn(tableId);
        page.setLimit(1000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> tableList = creditRepairService.getCfRecordsByConditionForPage("t_" + resourceId,
                showColumns, null, condition, page, String.valueOf(officeId));
        List<OptionalColumn> optionalColumns = columnService.getOptionalColumnByTableId(tableId);
        List<OptionalColumn> filter = filter(optionalColumns, defaultShowColumn);
        ExcelUtil.downloadExcel(response, tableList, "信用修复行政处罚列表", "信用修复行政处罚列表", showColumns, filter);
    }

    /**
     * 功能描述: 根据资源id获取默认展示列
     *
     * @param tableId 资源id
     * @return 默认展示列
     * @author YaoS
     * @date 19/4/10 10:18
     */
    private String[] getDefaultShowColumn(Integer tableId) {
        String[] defaultShowColumn = null;
        if (CreditRepairType.FR_XZCF.equals(tableId)) {
            defaultShowColumn = CreditRepairType.FR_CF_SHOW_COLUMN;
        } else if (CreditRepairType.ZRR_XZCF.equals(tableId)) {
            defaultShowColumn = CreditRepairType.ZRR_CF_SHOW_COLUMN;
        } else if (CreditRepairType.FR_HEI.equals(tableId)) {
            defaultShowColumn = CreditRepairType.FR_HEI_SHOW_COLUMN;
        } else if (CreditRepairType.ZRR_HEI.equals(tableId)) {
            defaultShowColumn = CreditRepairType.ZRR_HEI_SHOW_COLUMN;
        }
        return defaultShowColumn;
    }

    /**
     * 功能描述: 根据字段信息和默认展示信息返回展示列
     *
     * @param optionalColumnByTableId 列信息
     * @param defaultShowColumns      默认展示列
     * @return 默认展示列信息
     * @author YaoS
     * @date 19/4/10 10:25
     */
    private List<OptionalColumn> filter(List<OptionalColumn> optionalColumnByTableId, String[] defaultShowColumns) {
        List<OptionalColumn> columns = new ArrayList<>();
        for (OptionalColumn optionalColumn : optionalColumnByTableId) {
            for (String defaultShowColumn : defaultShowColumns) {
                if (defaultShowColumn.equals(optionalColumn.getColNameEN())) {
                    columns.add(optionalColumn);
                    break;
                }
            }
        }
        return columns;
    }
    
    /**
	 * 信用修复更新定时任务
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/updateRepairHistoryTask.do")
	public RestServiceResult<Object> updateRepairHistoryTask() {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			Object data = creditRepairService.updateRepairHistoryTask();
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("CreditRepairController#updateRepairHistoryTask", "信用修复更新定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("信用修复更新定时任务异常！");
			return result;
		}
	}
}
